package cn.kgc.listener;

import cn.kgc.service.ConsumerMessageInfoService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author wangyue
 * @version 1.0
 * 从死信队列中获得信息,条件是必须使用死信队列(mq.enableHandleDlx)
 */
@Slf4j
@Component
@ConditionalOnProperty(value = "mq.enableHandleDlx")
public class DeadLetterMessageListener implements ChannelAwareMessageListener {
    @Resource
    private ConsumerMessageInfoService consumerMessageInfoService;

    /**
     * 从死信队列中获得消息
     */
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        //获得消息的id
        String messageId= message.getMessageProperties().getHeader("spring_returned_message_correlation");
        //将消息的状态改为dead状态
        consumerMessageInfoService.messageReceiveDead(messageId);
        //发送警告
        log.warn("警告:消息{}被拒绝,并进入死信队列",messageId);
        //从死信队列中删除此条消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
